package com.stox.client.ui.javafx.chartingy.widget;

import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;

import com.stox.client.ui.core.model.intf.Configurable;
import com.stox.client.ui.javafx.chartingy.model.plot.Data;
import com.stox.client.ui.javafx.chartingy.model.plot.Plot;
import com.stox.client.ui.javafx.core.util.CSS;
import com.stox.client.ui.javafx.core.util.UI;
import com.stox.shared.core.i18n.MessageSource;
import com.stox.shared.core.util.Constant;

public class PlotInfoPanel extends HBox implements EventHandler<MouseEvent>{

	private final Plot<?, ?> plot;
	protected final Button removeButton = UI.mediumCrossButton(MessageSource.get("Remove"));
	protected final Button editButton = UI.mediumGearButton(MessageSource.get("Edit"));
	protected final Label displayNameLabel = new Label();
	protected final Label valueLabel = new Label();

	public PlotInfoPanel(final Plot<?, ?> plot) {
		this.plot = plot;
		UI.style(this, CSS.plotInfoPanel);
		getChildren().add(removeButton);
		removeButton.setOnAction(new EventHandler<ActionEvent>() {
			@Override
			public void handle(final ActionEvent event) {
				plot.getChart().getPlots().remove(plot);
				if ((null != plot.getChart()) && plot.equals(plot.getChart().getPrimaryPlot())) {
					plot.getChart().setPrimaryPlot(null);
				}
			}
		});
		editButton.setOnAction(new EventHandler<ActionEvent>() {
			@Override
			public void handle(final ActionEvent event) {
				if (plot instanceof Configurable) {
					final Configurable configurable = (Configurable) plot;
					configurable.configure();
				}
			}
		});
		if (plot instanceof Configurable) {
			getChildren().add(editButton);
		}
		getChildren().add(displayNameLabel);
		HBox.setHgrow(displayNameLabel, Priority.ALWAYS);
		displayNameLabel.textProperty().bind(plot.displayNameProperty());
		displayNameLabel.textFillProperty().bind(plot.colorProperty());
		valueLabel.textFillProperty().bind(plot.colorProperty());
		
		getChildren().add(valueLabel);
		plot.chartingView().getSplitPane().addEventFilter(MouseEvent.MOUSE_DRAGGED, this);
		plot.chartingView().getSplitPane().addEventFilter(MouseEvent.MOUSE_MOVED, this);
	}
	
	@Override
	public void handle(MouseEvent event) {
		int index = plot.primaryChart().getDateAxis().getIndexForDisplay(event.getX());
		if ((0 <= index) && (index < plot.getData().size())) {
			Data<?,?> data = plot.getData().get(index);
			if(null != data){
				valueLabel.setText(Constant.numberFormat.format(data.getValue()));
			}
		}
	}

	public Button getRemoveButton() {
		return removeButton;
	}

	public Button getEditButton() {
		return editButton;
	}

	public Label getDisplayNameLabel() {
		return displayNameLabel;
	}
}
